import { defineStore } from 'pinia'
import {reqUserList} from '../reqest'
import compareDate from '../utils/compareDate'
const useListStore = defineStore('list',{
  state:() => ({
    userList:[],
    total:0,
    filteDatas:[]
  }),
  actions:{
    // 发请求，拿数据
    getUserList:async function(){
      let res =await reqUserList()
      if(res.code === 200){
        this.userList = res.data.userList
        this.filteDatas = res.data.userList.list
        this.total = res.data.total
      }
    },

    removeUser:function(id){
      this.userList.list = this.filteDatas.filter((item)=>item.id !== id)
    },
    
    // 数据筛选
    filteData: function(keyData){
      // console.log(keyData);
      let  {username,product,industry,startDate,endDate} = keyData
      // 没有过滤数据则返回所有数据
      if(!username && !product && !industry && !startDate && !endDate){
        this.filteDatas = this.userList.list
      }
      // 确定过滤关键字
      let keywords = []
      for(let key in keyData){
        if(keyData[key]){
          keywords.push(key)
        }
      }
      // 过滤后数据
      let data = []
      // 数据过滤1：过滤除了endDate
      data = this.userList.list.filter((item)=>{
        return keywords.every((key) => {
          let res1=true,res2=true,res3=true
          if(key === 'startDate'){
             res1  = compareDate(item[key],keyData[key])
          }else if(key === 'endDate'){
             res2 = true
          }else{
             res3 = item[key] === keyData[key].trim()
          } 
          if(res1 && res2 && res3) return true    
          return false
        })
      })

      if(data.length === 0 &&keywords.length ===0 &&endDate) data = this.userList.list
      
      if(endDate && endDate.trim()){
        data = data.filter((item) => {
          return compareDate(endDate,item.endDate)
        })
      }
      this.filteDatas = data
    }
  },
  getters:{
  }
})

export default useListStore